package com.neusoft.databus.core.config;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.client.loadbalancer.LoadBalancedRetryFactory;
import org.springframework.cloud.netflix.ribbon.SpringClientFactory;
import org.springframework.cloud.openfeign.ribbon.CachingSpringLoadBalancerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import com.netflix.loadbalancer.IRule;
import com.neusoft.databus.core.loadbalance.StatefulCachingSpringLoadBalancerFactory;
import com.neusoft.databus.core.loadbalance.StatefulRoundRobinRule;

import feign.Logger;

/**
 * 带状态的负载均衡实现
 *
 * @author sunchf
 * @date 2018年12月21日 上午10:38:54
 */
@Configuration
@ConditionalOnProperty(name = "databus.core.agent.loadBalance.stateful", havingValue = "true")
public class LoadBalanceConfiguration {

    @Bean
    Logger.Level feignLoggerLevel() {
        //这里记录所有，根据实际情况选择合适的日志level
        return Logger.Level.FULL;
    }

    @Bean
    public IRule ribbonRule() {
        return new StatefulRoundRobinRule(); // 自定义规则
    }

    @Bean
    @Primary
    public CachingSpringLoadBalancerFactory retryabeCachingLBClientFactory(SpringClientFactory factory,
            LoadBalancedRetryFactory retryFactory) {
        final CachingSpringLoadBalancerFactory cachingSpringLoadBalancerFactory =
                new StatefulCachingSpringLoadBalancerFactory(
                        factory, retryFactory);
        return cachingSpringLoadBalancerFactory;
    }

}
